package com.yt.core.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.IOException;

/**
 * Created by liujunshi on 16/1/1.
 */
public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

        private Log log = LogFactory.getLog(CustomPropertyPlaceholderConfigurer.class);

        public CustomPropertyPlaceholderConfigurer() {
        }

        public void setLocations(Resource[] locations) {
            if(locations != null) {
                String userDir = System.getProperty("user.dir");

                for(int i = 0; i < locations.length; ++i) {
                    try {
                        Resource e = locations[i];
                        String fileName = e.getFile().getPath();
                        String fileNameNoPath = e.getFile().getName();
                        if(fileName.startsWith("${user_dir}")) {
                            this.log.info("开始重新定位资源" + e);

                            try {
                                UrlResource var11 = new UrlResource("file://" + userDir + fileName.substring("${user_dir}".length(), fileName.length()));
                                locations[i] = var11;
                                if(!var11.getFile().exists()) {
                                    throw new IOException("没有找到文件" + fileNameNoPath);
                                }

                                this.log.info("重新定位资源" + var11 + "成功");
                            } catch (Exception var8) {
                                this.log.info("重新定位资源" + e + "失败:" + var8.getMessage());
                                this.log.info("开始重新定位资源" + e + "尝试从classpath中加载");
                                ClassPathResource var10 = new ClassPathResource(fileNameNoPath);
                                locations[i] = var10;
                                this.log.info("开始重新定位资源" + var10 + "尝试从classpath中加载成功");
                            }
                        }
                    } catch (IOException var9) {
                        var9.printStackTrace();
                    }
                }

                super.setLocations(locations);
            }

        }
    }
